package transaction02;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    /*私有构造方法 不可以在类外创建对象*/
    private JDBCUtils() {

    }
    /*数据库驱动常量*/
    private static String driver;
    /*数据库连接URL常量*/
    private static String url;
    /*数据库登录用户名常量*/
    private static String user;
    /*数据库登录密码常量*/
    private static String password;

    /*注册驱动,当JDBCUtils类加载的时候,会执行静态代码块,此时会注册驱动*/
    static{
        Properties properties = new Properties();
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*获取连接的静态方法*/
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    /*释放资源*/
    public static void release(Connection con, Statement statement, ResultSet rs) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
